package cn.weekimwee.firstlineofcodeforkotlin.unit8

import android.Manifest
import android.app.Activity
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.app.NotificationCompat
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_unit8.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException

/**
 * Created by wkw on 18-3-6.
 */
class Unit8Activity : BaseActivity() {
    var imageUri: Uri? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_unit8)
        val manager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        text.setOnClickListener {
            //            val bigText = NotificationCompat.BigTextStyle()
//                    .setBigContentTitle("da title")
//                    .bigText("我哦我哦我哦我哦我我我我哦我哦我哦我哦我我我我哦我哦我哦我哦我我我我哦我哦我哦我哦我我我我哦我哦我哦我哦我我我我哦我哦我哦我哦我我我我哦我哦我哦我哦我我我我哦我哦我哦我哦我我我我哦我哦我哦我哦我我我我哦我哦我哦我哦我我我")
//            val bigImage = NotificationCompat.BigPictureStyle()
//                    .bigPicture(BitmapFactory.decodeResource(resources,R.mipmap.ic_launcher))
//            val notification =NotificationCompat.Builder(this,"渠道")
////                    .setContentTitle("我是title")
////                    .setContentText("我是content")
//                    .setWhen(System.currentTimeMillis())
////                    .setSmallIcon(R.mipmap.ic_launcher)
////                    .setLargeIcon(BitmapFactory.decodeResource(resources,R.mipmap.ic_launcher))
//                    .setAutoCancel(true)
////                    .setSound(Uri.fromFile(File("/system/media/audio/ringtones/Luna.ogg")))//通知来时的声音
//                    .setVibrate(longArrayOf(0,200,200,200,200,200,200))//震动 除了第一个外一个震动一个静止
//                    .setLights(Color.RED,2000,1000)   //这些都可以用默认的代替，默认的会按照手机环境来选择用什么震动 铃声之类的
//                    .setDefaults(NotificationCompat.DEFAULT_ALL) //不知道为什么红米手机不亮闪烁灯
//                    .setContentIntent(PendingIntent.getActivity(this@Unit8Activity,0, Intent(this@Unit8Activity,NActivity::class.java),0))
//                    .setStyle(bigImage)
//                    .build()
//            manager.notify(1,notification)
            // manager.cancel(1)这种方法是按照id来关掉通知
            //fixme 不知道为什么style在红米上无效    其他的手机暂未测试
            manager.notify(1, NotificationCompat.Builder(this, "qudao")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("title")
                    .setContentText("content cotent content")
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    // 该方法在Android 4.1之前会被忽略
                    .setStyle(NotificationCompat.BigTextStyle()
                            .bigText("-------------------------------------------------->"))
                    .setContentIntent(PendingIntent.getActivity(this@Unit8Activity, 0, Intent(this@Unit8Activity, NActivity::class.java), 0))
                    .build())
        }
        openCamera.setOnClickListener {
            val outputIMage = File(externalCacheDir, "output_image.jpg")
            try {
                if (outputIMage.exists()) outputIMage.exists()
                outputIMage.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            imageUri = if (Build.VERSION.SDK_INT >= 24) {
                FileProvider.getUriForFile(this@Unit8Activity, "cn.weekimwee.firstlineofcodeforkotlin.fileprovider", outputIMage)
            } else {
                Uri.fromFile(outputIMage)
            }
            startActivityForResult(Intent("android.media.action.IMAGE_CAPTURE").putExtra(MediaStore.EXTRA_OUTPUT, imageUri), 1)
        }
        choice.setOnClickListener {
            if (ContextCompat.checkSelfPermission(this@Unit8Activity,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this@Unit8Activity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
            } else {
                openAlbum()
            }
        }
        start.setOnClickListener {
            startActivity<NActivity>()
        }
        startVideo.setOnClickListener {
            startActivity<PlayVideoActivity>()
        }
    }

    private fun openAlbum() {
        startActivityForResult(Intent("android.intent.action.GET_CONTENT").setType("image/*"), 2)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum()
                } else {
                    toast("you denied the permission")
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            1 -> {
                try {
                    imageView.setImageBitmap(BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri)))
                } catch (e: FileNotFoundException) {
                    e.printStackTrace()
                }
            }
            2 -> {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat(data)
                } else {
                    handleImageBeforeKitKat(data)
                }
            }
        }
    }

    private fun handleImageBeforeKitKat(data: Intent) {
        val uri = data.data
        displayImage(getImagePath(uri,null))
    }

    private fun handleImageOnKitKat(data: Intent) {
        var imagePath =""
        val uri = data.data
        if (DocumentsContract.isDocumentUri(this@Unit8Activity, uri)) {
            //如果是document类型的uri，则通过document id处理
            val docId = DocumentsContract.getDocumentId(uri)
            if ("com.android.providers.media.documents" == uri.authority) {
                val id = docId.split(":")[1]
                val selection = MediaStore.Images.Media._ID + "=" + id
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)
            } else if ("com.android.providers.downloads.documents" == uri.authority) {
                val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),docId.toLong())
                imagePath = getImagePath(contentUri, null)
            }
        }else if("content".equals(uri.scheme,true)){
            //如果是content类型的uri，直接获取图片路径即可
            imagePath = getImagePath(uri,null)
        }else if("file".equals(uri.scheme,true)){
            //如果是file类型的uri，直接获取图片路径即可
            imagePath = uri.path
        }
        displayImage(imagePath)
    }

    private fun displayImage(imagePath: String) {
        if(imagePath.isNotBlank()){
            imageView.setImageBitmap(BitmapFactory.decodeFile(imagePath))
        }else{
            toast("failed to get image")
        }
    }

    private fun getImagePath(uri: Uri, selection: String?): String {
        //通过uri和selection来获取真实的图片路径
        var path =""
        val cursor= contentResolver.query(uri,null,selection,null,null)
        if(cursor!=null){
            if(cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
            }
            cursor.close()
        }
        return path
    }
}